import type { ComponentStyleIdType } from '../../../../types/interfaces'
import type { GreasyForkPageType } from '../../../page_handler/platform/greasyfork/types'
import {
  ComponentStyleId,
  getNerdFontsCSSContent,
  HOSTNAME,
  logger,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
  themeClassPrefix,
} from '../../../../types/constants'
import { TITLE_SELECTOR_MAPPING } from '../../../../types/constants/styles/title/config'
import { SYMBOLS, ThemeSourceMode, ThemeType } from '../../../../types/interfaces'
import { IconService } from '../../../icons'
import { PageHandler } from '../../../page_handler'
import { createStandardStyleTag } from '../../../style_injector'
import { ToolKit } from '../../../utils/toolkit'
import { PageManager } from '../../page_manager'
import { ColorService } from '../color_service'
import { ThemeVarService } from './service'

export class ThemeVar extends ColorService {
  private observer: MutationObserver | null = null
  private styleElement: HTMLStyleElement | null = null
  private styleId: string = ComponentStyleId[this.name]
  private static instance: ThemeVar
  private readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()
  private readonly iconService: IconService = IconService.getInstance()
  private readonly pageManager: PageManager = PageManager.getInstance()
  private readonly allThemeClass = Object.values(ThemeType).map(theme => `${themeClassPrefix}-${theme}`).join(' ')

  get name(): ComponentStyleIdType {
    return 'ThemeVar'
  }

  /**
   * 初始化主题监听
   */
  private initThemeObserver(): void {
    this.observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
          const oldValue = ToolKit.browser.theme.extractThemeValue(mutation.oldValue || '')
          const newValue = ToolKit.browser.theme.getCurrentTheme(ThemeSourceMode.INLINE)

          if (oldValue !== newValue) {
            this.updateTheme(newValue)
          }
        }
      }
    })

    // 开始观察 html 元素的 style 属性
    this.observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['style'],
      attributeOldValue: true,
    })
  }

  /**
   * 停止监听主题变化
   */
  disconnectThemeObserver(): void {
    this.observer?.disconnect()
    this.observer = null
  }

  /**
   * 获取单例实例
   */
  static getInstance(): ThemeVar {
    if (!ThemeVar.instance) {
      ThemeVar.instance = new ThemeVar()
    }
    return ThemeVar.instance
  }

  commonStyleVar(theme: ThemeType): string {
    return `
/* ${ToolKit.string.capitalizeFirstLetter(theme)} Theme Variables */
/* 基础色系 */
--${PROJECT_PREFIX}-theme-primary: ${this.getColorValue(theme, 'primary')};
--${PROJECT_PREFIX}-theme-secondary: ${this.getColorValue(theme, 'secondary')};
--${PROJECT_PREFIX}-theme-accent: ${this.getColorValue(theme, 'accent')};

/* 背景层级 */
--${PROJECT_PREFIX}-theme-bg-base: ${this.getColorValue(theme, 'backgroundBase')};
--${PROJECT_PREFIX}-theme-bg-surface: ${this.getColorValue(theme, 'backgroundSurface')};
--${PROJECT_PREFIX}-theme-bg-overlay: ${this.getColorValue(theme, 'backgroundOverlay')};
--${PROJECT_PREFIX}-theme-bg-preview: ${this.getColorValue(theme, 'backgroundPreview')};
--${PROJECT_PREFIX}-theme-bg-highlight: ${this.getColorValue(theme, 'backgroundHighlight')};
--${PROJECT_PREFIX}-theme-bg-fixed: ${this.getColorValue(theme, 'backgroundFixed')};
--${PROJECT_PREFIX}-theme-bg-list: ${this.getColorValue(theme, 'backgroundList')};
--${PROJECT_PREFIX}-theme-bg-left: ${this.getColorValue(theme, 'discussionBgOdd')};
--${PROJECT_PREFIX}-theme-bg-right: ${this.getColorValue(theme, 'discussionBgEven')};

/* 文本颜色 */
--${PROJECT_PREFIX}-theme-text-base: ${this.getColorValue(theme, 'textBase')};
--${PROJECT_PREFIX}-theme-text-primary: ${this.getColorValue(theme, 'textPrimary')};
--${PROJECT_PREFIX}-theme-text-secondary: ${this.getColorValue(theme, 'textSecondary')};
--${PROJECT_PREFIX}-theme-text-hint: ${this.getColorValue(theme, 'textHint')};
--${PROJECT_PREFIX}-theme-text-neutral: ${this.getColorValue(theme, 'textNeutral')};

/* 交互状态颜色 */
--${PROJECT_PREFIX}-theme-hover-primary: ${this.getColorValue(theme, 'hoverPrimary')};
--${PROJECT_PREFIX}-theme-active: ${this.getColorValue(theme, 'active')};
--${PROJECT_PREFIX}-theme-disabled: ${this.getColorValue(theme, 'disabled')};
--${PROJECT_PREFIX}-theme-selection-bg: ${this.getColorValue(theme, 'selectionBg')};
--${PROJECT_PREFIX}-theme-selection-text: ${this.getColorValue(theme, 'selectionText')};
--${PROJECT_PREFIX}-highlight-color: ${this.getColorValue(theme, 'highlightColor')};
${this.themeVarService.em.text}: ${this.getColorValue(theme, 'emText')};
${this.themeVarService.em.textHover}: ${this.getColorValue(theme, 'emTextHover')};

/* 语义状态颜色 */
--${PROJECT_PREFIX}-theme-success-bg: ${this.getColorValue(theme, 'successBg')};
--${PROJECT_PREFIX}-theme-success-text: ${this.getColorValue(theme, 'successText')};
--${PROJECT_PREFIX}-theme-success-secondary-text: ${this.getColorValue(theme, 'successSecondaryText')};
--${PROJECT_PREFIX}-theme-success-border: ${this.getColorValue(theme, 'successBorder')};
--${PROJECT_PREFIX}-theme-danger-bg: ${this.getColorValue(theme, 'dangerBg')};
--${PROJECT_PREFIX}-theme-danger-secondary-text: ${this.getColorValue(theme, 'dangerSecondaryText')};
--${PROJECT_PREFIX}-theme-danger-text: ${this.getColorValue(theme, 'dangerText')};
--${PROJECT_PREFIX}-theme-danger-border: ${this.getColorValue(theme, 'dangerBorder')};
--${PROJECT_PREFIX}-theme-warning-bg: ${this.getColorValue(theme, 'warningBg')};
--${PROJECT_PREFIX}-theme-warning-text: ${this.getColorValue(theme, 'warningText')};
--${PROJECT_PREFIX}-theme-warning-secondary-text: ${this.getColorValue(theme, 'warningSecondaryText')};
--${PROJECT_PREFIX}-theme-warning-border: ${this.getColorValue(theme, 'warningBorder')};
--${PROJECT_PREFIX}-theme-info-bg: ${this.getColorValue(theme, 'infoBg')};
--${PROJECT_PREFIX}-theme-info-text: ${this.getColorValue(theme, 'infoText')};
--${PROJECT_PREFIX}-theme-info-secondary-text: ${this.getColorValue(theme, 'infoSecondaryText')};
--${PROJECT_PREFIX}-theme-info-border: ${this.getColorValue(theme, 'infoBorder')};
--${PROJECT_PREFIX}-theme-orange-bg: ${this.getColorValue(theme, 'orangeBg')};
--${PROJECT_PREFIX}-theme-orange-text: ${this.getColorValue(theme, 'orangeText')};
--${PROJECT_PREFIX}-theme-orange-secondary-text: ${this.getColorValue(theme, 'orangeSecondaryText')};
--${PROJECT_PREFIX}-theme-orange-border: ${this.getColorValue(theme, 'orangeBorder')};
--${PROJECT_PREFIX}-theme-purple-bg: ${this.getColorValue(theme, 'purpleBg')};
--${PROJECT_PREFIX}-theme-purple-text: ${this.getColorValue(theme, 'purpleText')};
--${PROJECT_PREFIX}-theme-purple-secondary-text: ${this.getColorValue(theme, 'purpleSecondaryText')};
--${PROJECT_PREFIX}-theme-purple-border: ${this.getColorValue(theme, 'purpleBorder')};

/* 边框与阴影 */
--${PROJECT_PREFIX}-theme-border-neutral: ${this.getColorValue(theme, 'borderNeutral')};
--${PROJECT_PREFIX}-theme-border-primary: ${this.getColorValue(theme, 'borderPrimary')};
--${PROJECT_PREFIX}-theme-border-secondary: ${this.getColorValue(theme, 'borderSecondary')};
--${PROJECT_PREFIX}-theme-border-active: ${this.getColorValue(theme, 'borderActive')};
--${PROJECT_PREFIX}-theme-shadow-sm: ${this.getColorValue(theme, 'shadowSm')};
--${PROJECT_PREFIX}-theme-shadow-md: ${this.getColorValue(theme, 'shadowMd')};
--${PROJECT_PREFIX}-theme-shadow-lg: ${this.getColorValue(theme, 'shadowLg')};

/* 徽章 */
${this.themeVarService.badge.green.background}: ${this.getColorValue(theme, 'badgeGreenBg')};
${this.themeVarService.badge.green.text}: ${this.getColorValue(theme, 'badgeGreenText')};
${this.themeVarService.badge.green.borderColor}: ${this.getColorValue(theme, 'badgeGreenBorderColor')};
${this.themeVarService.badge.red.background}: ${this.getColorValue(theme, 'badgeRedBg')};
${this.themeVarService.badge.red.text}: ${this.getColorValue(theme, 'badgeRedText')};
${this.themeVarService.badge.red.borderColor}: ${this.getColorValue(theme, 'badgeRedBorderColor')};

/* 滚动条 */
--${PROJECT_PREFIX}-theme-scrollbar-thumb-bg: ${this.getColorValue(theme, 'scrollbarThumbBg')};
--${PROJECT_PREFIX}-theme-scrollbar-thumb-border-color: ${this.getColorValue(theme, 'scrollbarThumbBorderColor')};
--${PROJECT_PREFIX}-theme-scrollbar-track-bg: ${this.getColorValue(theme, 'scrollbarTrackBg')};
--${PROJECT_PREFIX}-theme-scrollbar-vertical-width: 6px;
--${PROJECT_PREFIX}-theme-scrollbar-horizontal-width: 8px;
--${PROJECT_PREFIX}-theme-scrollbar-margin-left: 5px;
--${PROJECT_PREFIX}-theme-scrollbar-radius: 3px;

/* 滚动按钮 */
--${PROJECT_PREFIX}-theme-scroll-button-bg: ${this.getColorValue(theme, 'scrollButtonBg')};
--${PROJECT_PREFIX}-theme-scroll-button-bg-hover: ${this.getColorValue(theme, 'scrollButtonBgHover')};

/* 用户名 */
--${PROJECT_PREFIX}-theme-username-color: ${this.getColorValue(theme, 'usernameColor')};

/* 导航栏 */
--${PROJECT_PREFIX}-theme-navbar-bg: ${this.getColorValue(theme, 'navbarBg')};
--${PROJECT_PREFIX}-theme-navbar-dropdown-bg: ${this.getColorValue(theme, 'navbarDropdownBg')};
--${PROJECT_PREFIX}-theme-navbar-dropdown-hover-bg: ${this.getColorValue(theme, 'navbarDropdownHoverBg')};
--${PROJECT_PREFIX}-theme-navbar-active-text: ${this.getColorValue(theme, 'navbarActiveText')};
--${PROJECT_PREFIX}-theme-navbar-hover-text: ${this.getColorValue(theme, 'navbarHoverText')};

/* 目录 */
--${PROJECT_PREFIX}-theme-toc-bg: ${this.getColorValue(theme, 'tocBg')};
--${PROJECT_PREFIX}-theme-toc-text: ${this.getColorValue(theme, 'tocText')};
--${PROJECT_PREFIX}-theme-toc-li-active-text: ${this.getColorValue(theme, 'tocLiActiveText')};
--${PROJECT_PREFIX}-theme-toc-li-hover-bg: ${this.getColorValue(theme, 'tocLiHoverBg')};
--${PROJECT_PREFIX}-theme-toc-li-hover-text: ${this.getColorValue(theme, 'tocLiHoverText')};

/* 页面净化 */
--${PROJECT_PREFIX}-theme-ad-bg: ${this.getColorValue(theme, 'adBg')};
--${PROJECT_PREFIX}-theme-ad-text: ${this.getColorValue(theme, 'adText')};
--${PROJECT_PREFIX}-theme-ad-button-bg: ${this.getColorValue(theme, 'adButtonBg')};
--${PROJECT_PREFIX}-theme-ad-button-text: ${this.getColorValue(theme, 'adButtonText')};
--${PROJECT_PREFIX}-theme-ad-counter-text: ${this.getColorValue(theme, 'adCounterText')};

/* 分页条 */
${this.themeVarService.pageBar.currentPage.bg}: ${this.getColorValue(theme, 'pageBarCurrentPageBg')};
${this.themeVarService.pageBar.currentPage.text}: ${this.getColorValue(theme, 'pageBarCurrentPageText')};
${this.themeVarService.pageBar.otherPage.bg}: ${this.getColorValue(theme, 'pageBarOtherPageBg')};
${this.themeVarService.pageBar.otherPage.text}: ${this.getColorValue(theme, 'pageBarOtherPageText')};
${this.themeVarService.pageBar.otherPage.bgHover}: ${this.getColorValue(theme, 'pageBarOtherPageBgHover')};
${this.themeVarService.pageBar.otherPage.textHover}: ${this.getColorValue(theme, 'pageBarOtherPageTextHover')};

/* 标签页 */
${this.themeVarService.tab.textActive}: ${this.getColorValue(theme, 'tabActiveText')};
${this.themeVarService.tab.borderActive}: ${this.getColorValue(theme, 'tabActiveBorder')};
${this.themeVarService.tab.textHover}: ${this.getColorValue(theme, 'tabHoverText')};
${this.themeVarService.tab.bgFocus}: ${this.getColorValue(theme, 'tabFocusBg')};

/* 工具栏 */
--${PROJECT_PREFIX}-theme-toolbar-bg: ${this.getColorValue(theme, 'toolbarBg')};
--${PROJECT_PREFIX}-theme-toolbar-filter-bg: ${this.getColorValue(theme, 'toolbarFilterBg')};
--${PROJECT_PREFIX}-theme-toolbar-shadow-bg: ${this.getColorValue(theme, 'toolbarShadowBg')};
--${PROJECT_PREFIX}-theme-toolbar-button-bg: ${this.getColorValue(theme, 'toolbarButtonBg')};
--${PROJECT_PREFIX}-theme-toolbar-button-bg-hover: ${this.getColorValue(theme, 'toolbarButtonBgHover')};
--${PROJECT_PREFIX}-theme-toolbar-button-text: ${this.getColorValue(theme, 'toolbarButtonText')};
--${PROJECT_PREFIX}-theme-toolbar-answer-floor-bg: ${this.getColorValue(theme, 'toolbarAnswerFloorBg')};
--${PROJECT_PREFIX}-theme-toolbar-answer-floor-text: ${this.getColorValue(theme, 'toolbarAnswerFloorText')};
--${PROJECT_PREFIX}-theme-toolbar-answer-time-text: ${this.getColorValue(theme, 'toolbarAnswerTimeText')};
--${PROJECT_PREFIX}-theme-dropdown-bg: ${this.getColorValue(theme, 'dropdownBg')};
--${PROJECT_PREFIX}-theme-dropdown-text: ${this.getColorValue(theme, 'dropdownText')};
--${PROJECT_PREFIX}-theme-dropdown-bg-hover: ${this.getColorValue(theme, 'dropdownBgHover')};
--${PROJECT_PREFIX}-theme-dropdown-border: ${this.getColorValue(theme, 'dropdownBorder')};

/* 搜索相关 */
--${PROJECT_PREFIX}-theme-search-history-text: ${this.getColorValue(theme, 'searchHistoryText')};
--${PROJECT_PREFIX}-theme-search-suggestions-text: ${this.getColorValue(theme, 'searchSuggestionsText')};
--${PROJECT_PREFIX}-theme-search-result-item-bg: ${this.getColorValue(theme, 'searchResultItemBg')};
--${PROJECT_PREFIX}-theme-search-result-item-bg-official: ${this.getColorValue(theme, 'searchResultItemBgOfficial')};
--${PROJECT_PREFIX}-theme-search-result-item-bg-popular: ${this.getColorValue(theme, 'searchResultItemBgPopular')};
--${PROJECT_PREFIX}-theme-search-result-item-shadow: ${this.getColorValue(theme, 'searchResultItemShadow')};

/* 讨论卡片 */
--${PROJECT_PREFIX}-theme-discussion-bg-odd: ${this.getColorValue(theme, 'discussionBgOdd')};
--${PROJECT_PREFIX}-theme-discussion-bg-even: ${this.getColorValue(theme, 'discussionBgEven')};
--${PROJECT_PREFIX}-theme-discussion-shadow-odd: ${this.getColorValue(theme, 'discussionShadowOdd')};
--${PROJECT_PREFIX}-theme-discussion-shadow-even: ${this.getColorValue(theme, 'discussionShadowEven')};
--${PROJECT_PREFIX}-theme-discussion-shadow-hover-odd: ${this.getColorValue(theme, 'discussionShadowHoverOdd')};
--${PROJECT_PREFIX}-theme-discussion-shadow-hover-even: ${this.getColorValue(theme, 'discussionShadowHoverEven')};
--${PROJECT_PREFIX}-theme-discussion-bg-author: ${this.getColorValue(theme, 'discussionBgAuthor')};
--${PROJECT_PREFIX}-theme-discussion-shadow-author: ${this.getColorValue(theme, 'discussionShadowAuthor')};
--${PROJECT_PREFIX}-theme-discussion-bg-mine: ${this.getColorValue(theme, 'discussionBgMine')};
--${PROJECT_PREFIX}-theme-discussion-shadow-mine: ${this.getColorValue(theme, 'discussionShadowMine')};
--${PROJECT_PREFIX}-theme-discussion-bg-original-poster: ${this.getColorValue(theme, 'discussionBgOriginalPoster')};
--${PROJECT_PREFIX}-theme-discussion-shadow-original-poster: ${this.getColorValue(theme, 'discussionShadowOriginalPoster')};

/* 下拉框 */
--${PROJECT_PREFIX}-theme-select-bg: ${this.getColorValue(theme, 'selectBg')};
--${PROJECT_PREFIX}-theme-select-active-bg: ${this.getColorValue(theme, 'selectActiveBg')};
--${PROJECT_PREFIX}-theme-select-text: ${this.getColorValue(theme, 'selectText')};
--${PROJECT_PREFIX}-theme-select-active-text: ${this.getColorValue(theme, 'selectTextActive')};
--${PROJECT_PREFIX}-theme-select-option-bg: ${this.getColorValue(theme, 'selectOptionBg')};
--${PROJECT_PREFIX}-theme-select-option-text: ${this.getColorValue(theme, 'selectOptionText')};
--${PROJECT_PREFIX}-theme-select-option-checked-bg: ${this.getColorValue(theme, 'selectOptionCheckedBg')};
--${PROJECT_PREFIX}-theme-select-option-checked-text: ${this.getColorValue(theme, 'selectOptionCheckedText')};
--${PROJECT_PREFIX}-theme-select-option-disabled-text: ${this.getColorValue(theme, 'selectOptionDisabledText')};

/* 搜索框 */
--${PROJECT_PREFIX}-theme-search-bg: ${this.getColorValue(theme, 'searchBg')};
--${PROJECT_PREFIX}-theme-search-text: ${this.getColorValue(theme, 'searchText')};

/* 文本框 */
--${PROJECT_PREFIX}-theme-text-text: ${this.getColorValue(theme, 'textText')};
/* 文本光标 */
--${PROJECT_PREFIX}-theme-text-caret: ${this.getColorValue(theme, 'textCaret')};
/* 文本域 */
--${PROJECT_PREFIX}-theme-textarea-text: ${this.getColorValue(theme, 'textareaText')};

/* 链接 */
${this.themeVarService.link.default.text}: ${this.getColorValue(theme, 'linkText')};
${this.themeVarService.link.default.textHover}: ${this.getColorValue(theme, 'linkHover')};
${this.themeVarService.link.default.textVisited}: ${this.getColorValue(theme, 'linkVisited')};

/* 公告 */
--${PROJECT_PREFIX}-theme-announcement-bg: ${this.getColorValue(theme, 'announcementBg')};
--${PROJECT_PREFIX}-theme-announcement-text: ${this.getColorValue(theme, 'announcementText')};

/* 评论 */
--${PROJECT_PREFIX}-theme-comment-bg: ${this.getColorValue(theme, 'commentBg')};
--${PROJECT_PREFIX}-theme-comment-text: ${this.getColorValue(theme, 'commentText')};

/* 阅读 */
--${PROJECT_PREFIX}-theme-read-bg: ${this.getColorValue(theme, 'readBg')};

/* 回答 */
--${PROJECT_PREFIX}-theme-answer-bg: ${this.getColorValue(theme, 'answerBg')};
--${PROJECT_PREFIX}-theme-answer-loading-bg: ${this.getColorValue(theme, 'answerLoadingBg')};
--${PROJECT_PREFIX}-theme-answer-switch-mask-bg: ${this.getColorValue(theme, 'answerSwitchMaskBg')};
--${PROJECT_PREFIX}-theme-answer-switch-mask-text: ${this.getColorValue(theme, 'answerSwitchMaskText')};

/* 加载弹窗 */
--${PROJECT_PREFIX}-theme-loading-alert-bg: ${this.getColorValue(theme, 'loadingAlertBg')};
--${PROJECT_PREFIX}-theme-loading-alert-text: ${this.getColorValue(theme, 'loadingAlertText')};

/* 特殊元素 */
/* 作者 */
--${PROJECT_PREFIX}-theme-author-bg: ${this.getColorValue(theme, 'authorBackground')};
--${PROJECT_PREFIX}-theme-author-shadow: ${this.getColorValue(theme, 'authorShadow')};
/* 标签 */
--${PROJECT_PREFIX}-theme-tag-text: ${this.getColorValue(theme, 'tagText')};
--${PROJECT_PREFIX}-theme-tag-bg: ${this.getColorValue(theme, 'tagBackground')};
--${PROJECT_PREFIX}-theme-tag-bg-hover: ${this.getColorValue(theme, 'tagBackgroundHover')};
--${PROJECT_PREFIX}-theme-tag-border: ${this.getColorValue(theme, 'tagBorder')};
--${PROJECT_PREFIX}-theme-tag-shadow: ${this.getColorValue(theme, 'tagShadow')};
--${PROJECT_PREFIX}-theme-tag-shadow-hover: ${this.getColorValue(theme, 'tagShadowHover')};
${this.themeVarService.tag.blue.text}: ${this.getColorValue(theme, 'tagBlueText')};
${this.themeVarService.tag.blue.textHover}: ${this.getColorValue(theme, 'tagBlueTextHover')};
${this.themeVarService.tag.blue.bg}: ${this.getColorValue(theme, 'tagBlueBg')};
${this.themeVarService.tag.blue.bgHover}: ${this.getColorValue(theme, 'tagBlueBgHover')};
/* 链接 */
--${PROJECT_PREFIX}-theme-link-card-bg: ${this.getColorValue(theme, 'linkCardBg')};
--${PROJECT_PREFIX}-theme-link-card-text: ${this.getColorValue(theme, 'linkCardText')};
--${PROJECT_PREFIX}-theme-link-card-shadow: ${this.getColorValue(theme, 'linkCardShadow')};
/* 水平分割线 */
--${PROJECT_PREFIX}-theme-hr-bg: ${this.getColorValue(theme, 'hrBackground')};
/* 代码块 */
--${PROJECT_PREFIX}-theme-code-text-common: ${this.getColorValue(theme, 'codeTextCommon')};
--${PROJECT_PREFIX}-theme-code-toolbar-divider: ${this.getColorValue(theme, 'codeToolbarDivider')};
--${PROJECT_PREFIX}-theme-code-text-primary: ${this.getColorValue(theme, 'codeTextPrimary')};
--${PROJECT_PREFIX}-theme-code-text-secondary: ${this.getColorValue(theme, 'codeTextSecondary')};
--${PROJECT_PREFIX}-theme-code-shadow-hover: ${this.getColorValue(theme, 'codeShadowHover')};
--${PROJECT_PREFIX}-theme-code-hide-bg: ${this.getColorValue(theme, 'codeHideBg')};
--${PROJECT_PREFIX}-theme-code-toolbar-bg: ${this.getColorValue(theme, 'codeToolbarBg')};
--${PROJECT_PREFIX}-theme-code-bg: ${this.getColorValue(theme, 'codeBg')};
--${PROJECT_PREFIX}-theme-code-diff-bg: ${this.getColorValue(theme, 'codeDiffBg')};
/* 标记 */
--${PROJECT_PREFIX}-theme-mark-bg: ${this.getColorValue(theme, 'markBackground')};
--${PROJECT_PREFIX}-theme-mark-text: ${this.getColorValue(theme, 'markText')};
/* 引用 */
--${PROJECT_PREFIX}-theme-quote-bg: ${this.getColorValue(theme, 'quoteBackground')};
--${PROJECT_PREFIX}-theme-quote-text: ${this.getColorValue(theme, 'quoteText')};
/* 表格 */
--${PROJECT_PREFIX}-theme-table-header-bg: ${this.getColorValue(theme, 'tableHeaderBg')};
--${PROJECT_PREFIX}-theme-table-heading-text: ${this.getColorValue(theme, 'tableHeadingText')};
--${PROJECT_PREFIX}-theme-table-cell-border: ${this.getColorValue(theme, 'tableCellBorder')};
--${PROJECT_PREFIX}-theme-table-row-odd-bg: ${this.getColorValue(theme, 'tableRowOddBg')};
--${PROJECT_PREFIX}-theme-table-row-even-bg: ${this.getColorValue(theme, 'tableRowEvenBg')};
--${PROJECT_PREFIX}-theme-table-row-hover-bg: ${this.getColorValue(theme, 'tableRowHoverBg')};
--${PROJECT_PREFIX}-theme-table-row-hover-text: ${this.getColorValue(theme, 'tableRowHoverText')};
--${PROJECT_PREFIX}-theme-table-highlight-bg: ${this.getColorValue(theme, 'tableHighlightBg')};

/* 快捷键 */
--${PROJECT_PREFIX}-theme-kbd-bg: ${this.getColorValue(theme, 'kbdBg')};
--${PROJECT_PREFIX}-theme-kbd-text: ${this.getColorValue(theme, 'kbdText')};
/* 注脚 */
--${PROJECT_PREFIX}-theme-footnote-text: ${this.getColorValue(theme, 'footnoteText')};
/* 缩写 */
--${PROJECT_PREFIX}-theme-abbr-text: ${this.getColorValue(theme, 'abbrText')};
`
  }

  getStyleVar(theme: ThemeType): string {
    return `:root {
${this.commonStyleVar(theme)}
}
`
  }

  init(): void {
    if (this.styleElement)
      return

    const theme = this.pageManager.getEffectTheme()
    const styleContent = this.getStyleVar(theme)

    this.styleElement = createStandardStyleTag(this.styleId, styleContent)
    this.initThemeObserver()

    this.applyFontStyle()

    // 应用图标样式
    this.iconService.applyStyle()
    logger.tip(`[${this.name}] 图标校验结果`, this.iconService.getValidateStats())
    logger.tip(`[${this.name}] 图标统计结果`, this.iconService.getIconStats())
  }

  /**
   * 应用字体样式
   */
  applyFontStyle(): void {
    if (![SUPPORTED_PLATFORMS.GITEE].includes(HOSTNAME))
      return

    const cssContent = getNerdFontsCSSContent()
    createStandardStyleTag(ComponentStyleId.NerdFonts, cssContent)

    logger.info(`[${this.name}] ${SYMBOLS.STATUS.SUCCESS} 字体样式已加载`)
  }

  /**
   * 更新主题样式
   */
  updateTheme(theme: ThemeType): void {
    this.updatePersonalizationTitleTheme(theme)
    this.updateTitleTheme(theme)

    if (!this.styleElement) {
      logger.warn(`[${this.name}] 样式元素不存在：id='${this.styleId}'`)
      return
    }

    this.styleElement.textContent = this.getStyleVar(theme)
  }

  /**
   * 更新用户中心标题主题
   */
  updatePersonalizationTitleTheme(theme: ThemeType): void {
    const currentThemeClass = `${themeClassPrefix}-${theme}`

    // 个性化
    $('.personalization-settings .setting-group h3')
      .removeClass(this.allThemeClass)
      .addClass(currentThemeClass)
    // 网页增强
    $('.utility-settings .feature-category h3')
      .removeClass(this.allThemeClass)
      .addClass(currentThemeClass)
  }

  /**
   * 更新标题主题
   */
  updateTitleTheme(theme: ThemeType): void {
    const pageType = PageHandler.getCurrentPageType()

    Object.entries(TITLE_SELECTOR_MAPPING).forEach(([host, config]) => {
      if (host !== HOSTNAME)
        return

      Object.values(config).forEach((title) => {
        if (!Object.keys(title).includes(pageType))
          return

        const titleSelector = title[pageType as GreasyForkPageType]

        if (!titleSelector)
          return

        $(titleSelector).removeClass(this.allThemeClass).addClass(`${themeClassPrefix}-${theme}`)
      })
    })
  }
}
